using Microsoft.AspNetCore.Authentication.JwtBearer; // JWT 认证相关功能
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; // 数据库上下文和查询功能
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens; // JWT 令牌验证相关功能
using Microsoft.OpenApi.Models; // Swagger 相关功能
using System.Text; // 字符串编码功能
using UniversalAdmin.Application.Services;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories; // 领域层仓储接口

using UniversalAdmin.Infrastructure.Data.Contexts; // 数据库上下文
using UniversalAdmin.Infrastructure.Repositories; // 基础设施层仓储实现
using UniversalAdmin.Infrastructure.Services; // 基础设施层服务
using UniversalAdmin.Api.Middleware; // 自定义中间件

// 创建 WebApplication 构建器
var builder = WebApplication.CreateBuilder(args);

// 配置数据库上下文 - 性能优化
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"), npgsqlOptions =>
    {
        npgsqlOptions.CommandTimeout(30); // 设置命令超时时间
    });

    // 开发环境配置
    if (builder.Environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
    }
});

// 注册 JwtService
builder.Services.AddScoped<JwtService>();

// 注册 AuthService 登录注册登出
builder.Services.AddScoped<IAuthService, AuthService>();

// 注册 RoleService 角色管理
builder.Services.AddScoped<IRoleService, RoleService>();

// 注册 PermissionService 权限管理
builder.Services.AddScoped<IPermissionService, PermissionService>();

// 注册 UserService 用户管理
builder.Services.AddScoped<IUserService, UserService>();

// 注册 RolePermissionService 角色权限管理
builder.Services.AddScoped<IRolePermissionService, RolePermissionService>();

// 注册 PersonalService 个人资料管理
builder.Services.AddScoped<IPersonalService, PersonalService>();

// 注册 MenuService 菜单管理
builder.Services.AddScoped<IMenuService, MenuService>();

// 注册 SystemConfigService 系统配置管理
builder.Services.AddScoped<ISystemConfigService, SystemConfigService>();

// 注册 OperationLogService 操作日志管理
builder.Services.AddScoped<IOperationLogService, OperationLogService>();

// 注册 ArticleService 文章管理
builder.Services.AddScoped<IArticleService, ArticleService>();

// 注册 ArticleCategoryService 文章分类管理
builder.Services.AddScoped<IArticleCategoryService, ArticleCategoryService>();

// 注册 仓储实现类（依赖关系）
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IMenuRepository, MenuRepository>();
builder.Services.AddScoped<IMenuRoleRepository, MenuRoleRepository>();
builder.Services.AddScoped<ISystemConfigRepository, SystemConfigRepository>();
builder.Services.AddScoped<IOperationLogRepository, OperationLogRepository>();
builder.Services.AddScoped<IArticleRepository, ArticleRepository>();
builder.Services.AddScoped<IArticleCategoryRepository, ArticleCategoryRepository>();

// 配置 Identity 服务
builder.Services.AddIdentity<User, Role>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 替换默认的 PasswordHasher 为 BCryptPasswordHasher
builder.Services.Replace(
    ServiceDescriptor.Scoped<IPasswordHasher<User>, BCryptPasswordHasher<User>>());

// 配置 JWT 认证（改进版）
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };

    // 允许匿名访问
    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            return Task.CompletedTask;
        },

        OnTokenValidated = async context =>
        {
            // 跳过登录和注册接口的Token黑名单检查，提升性能
            var path = context.Request.Path.Value?.ToLower();
            if (path?.Contains("/auth/login") == true ||
                path?.Contains("/auth/register") == true)
            {
                return; // 跳过黑名单检查
            }

            var jwtService = context.HttpContext.RequestServices.GetRequiredService<JwtService>();
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            if (!string.IsNullOrEmpty(token))
            {
                // 只对非登录请求进行黑名单检查
                var isBlacklisted = await jwtService.ValidateTokenAsync(token);
                if (isBlacklisted == null)
                {
                    context.Fail("Token 无效或已被注销");
                }
            }
        },

        OnAuthenticationFailed = async context =>
        {
            if (context.Exception is SecurityTokenExpiredException)
            {
                context.Response.Headers.Append("Token-Expired", "true");
            }
            await Task.CompletedTask;
        }
    };
});

// 其他服务配置

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

// Swagger 配置（带 JWT 支持）
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "Auth API", Version = "v1" });

    // 添加 JWT 认证支持到 Swagger
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});

// CORS 配置
builder.Services.AddCors(options =>
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.WithOrigins("http://localhost:5173",
                         "http://localhost:3000",
                         "http://localhost:8080",
                         "http://localhost:4173",
                         "http://zzaisx.top:5173",
                        "http://admin-hcx.axuege.xyz:5173",
                        "http://admin-zjp.beiweijierui.xyz:5173",
                        "http://admin-yzy.wudkmao.top:5173",
                        "http://47.122.49.186:5173"
        )
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    }));

var app = builder.Build();

// 中间件管道配置
app.UseCors("AllowFrontend");

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 添加自定义中间件
app.UseMiddleware<UniversalAdmin.Api.Middleware.OperationLogMiddleware>();
app.UseMiddleware<UniversalAdmin.Api.Middleware.PermissionMiddleware>();

app.UseAuthentication();  // 必须在 UseAuthorization 之前
app.UseAuthorization();

app.MapControllers();



app.Run();